import { Component, OnInit } from '@angular/core'
import { FormBuilder, FormGroup, Validators } from '@angular/forms'
import { map } from 'rxjs/operators'
import { NzMessageService } from 'ng-zorro-antd'
import { SettingsService } from '@delon/theme'

import { GroupStoreService } from '../group-store.service'
import { GroupCommon, AgentFull } from '@shared/interfaces/group'
import { Contact } from '@shared/interfaces/contact'
import { INewSelectOption } from '@shared/interfaces/common'
import { GroupNewBaseClass } from '../baseClass'
import { makeAllControlDirty, getAAMSAcquirer, acquirerEditPermission } from 'app/utils/helpers'
import { IAamsItem } from '@shared/components/aams-select/aams-select.interface'
import {
  emailReg,
  agentNameENReg,
  agentNameMaxLength,
  agentNameENMaxLength,
  contactNameMaxLength,
  emailMaxLength,
} from 'app/utils/contraints'
import { User } from '@shared/interfaces/user'
import { I18NService } from '@core'

@Component({
  selector: 'app-group-new-base',
  templateUrl: './base.component.html',
  styleUrls: ['../../../../shared/styles/new-page-form.less'],
})
export class GroupNewBaseComponent extends GroupNewBaseClass implements OnInit {
  baseData: GroupCommon
  validateForm: FormGroup
  acquirerOptions: INewSelectOption[] = []
  chosenAcquirer: IAamsItem
  errorTips = {}

  constructor(
    public msg: NzMessageService,
    public fb: FormBuilder,
    public groupStore: GroupStoreService,
    public settings: SettingsService,
    private i18n: I18NService,
  ) {
    super(fb, groupStore)
  }

  ngOnInit(): void {
    this.groupStore.value$.pipe(map((agentFull: AgentFull) => agentFull.agent.common)).subscribe(group => {
      this.baseData = group
      const authUser = this.settings.user as User

      if (this.baseData.insCode) {
        this.chosenAcquirer = {
          num: this.baseData.insCode,
          code: this.baseData.insCode,
          name: this.baseData.insName,
          nameEN: this.baseData.insNameEN,
        }
      } else {
        this.chosenAcquirer = getAAMSAcquirer(authUser)
      }

      this.validateForm = this.fb.group({
        institution: [
          {
            value: this.chosenAcquirer.code ? this.chosenAcquirer : null,
            disabled: acquirerEditPermission(authUser),
          },
          [Validators.required],
        ],
        insName: [this.chosenAcquirer.name],
        insNameEN: [this.chosenAcquirer.nameEN],
        agentName: [this.baseData.agentName, [Validators.required, Validators.maxLength(agentNameMaxLength)]],
        agentNameEN: [
          this.baseData.agentNameEN,
          [Validators.required, Validators.maxLength(agentNameENMaxLength), Validators.pattern(agentNameENReg)],
        ],
        contactName: [this.baseData.contact.name, [Validators.required, Validators.maxLength(contactNameMaxLength)]],
        contactEmail: [
          this.baseData.contact.email,
          [Validators.required, Validators.maxLength(emailMaxLength), Validators.pattern(emailReg)],
        ],
      })
      this.initErrorTips()
    })
  }

  initErrorTips() {
    this.errorTips = {
      institution: {
        required: this.trans('VALIDATION.REQUIRED_SELECT', { name: this.trans('GENERAL.BIZ_LEVEL.INSTITUTION') }),
      },
      agentName: {
        required: this.trans('VALIDATION.REQUIRED', { name: this.trans('GENERAL.AGENT.NAME') }),
        maxlength: this.trans('VALIDATION.MAX_LENGTH', { length: agentNameMaxLength }),
      },
      agentNameEN: {
        required: this.trans('VALIDATION.REQUIRED', { name: this.trans('GENERAL.AGENT.NAME_EN') }),
        maxlength: this.trans('VALIDATION.MAX_LENGTH', { length: agentNameENMaxLength }),
        pattern: this.trans('VALIDATION.PATTERN.ALPHANUMERIC_SYMBOLS_ONLY'),
      },
      contactName: {
        required: this.trans('VALIDATION.REQUIRED', { name: this.trans('GENERAL.INFO.CONTACT_NAME') }),
        maxlength: this.trans('VALIDATION.MAX_LENGTH', { length: contactNameMaxLength }),
      },
      contactEmail: {
        required: this.trans('VALIDATION.REQUIRED', { name: this.trans('GENERAL.INFO.EMAIL') }),
        maxlength: this.trans('VALIDATION.MAX_LENGTH', { length: emailMaxLength }),
        pattern: this.trans('VALIDATION.PATTERN.EMAIL'),
      },
    }
  }

  checkValid(): boolean {
    const valid = this.validateForm.valid
    if (valid) {
      this.fullfilData(this.validateForm.value)
      this.pushDataToStore()
      this.msg.success(this.trans('GENERAL.NOTIFICATION.VALIDATION_SUCCESS'))
    } else {
      makeAllControlDirty(this.validateForm)
      this.msg.error(this.trans('GENERAL.NOTIFICATION.VALIDATION_FAIL'))
    }
    return valid
  }

  pushDataToStore(): void {
    const group = this.groupStore.value.agent.common
    Object.assign(group, this.baseData)
  }

  handleChosenAcquirer(acquirer): void {
    if (!acquirer) return
    this.validateForm.get('insName').setValue(acquirer.name)
    this.validateForm.get('insNameEN').setValue(acquirer.nameEN)
    this.chosenAcquirer = acquirer
  }

  trans(key: string, params?: Object): string {
    return this.i18n.fanyi(key, params)
  }

  private fullfilData(value): void {
    this.baseData.insCode = this.chosenAcquirer.code
    this.baseData.insName = this.chosenAcquirer.name
    this.baseData.insNameEN = this.chosenAcquirer.nameEN

    this.baseData.agentNameEN = value.agentNameEN
    this.baseData.agentName = value.agentName
    const contact = new Contact()
    contact.name = value.contactName
    contact.email = value.contactEmail
    this.baseData.contact = contact
  }
}
